<template>
  <div class="container" style="padding-bottom: 100px;">
    <div style="margin-bottom: 20px">
      <el-input style="width: 240px;margin-right: 20px;" placeholder="请输入文件名" v-model="name"></el-input>
      <el-button style="margin-left: 5px" type="primary" @click="loadAdminPage"><i class="el-icon-search"></i> 搜索</el-button>
      <el-button style="margin-left: 5px" type="warning" @click="reset"><i class="el-icon-refresh"></i> 重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-popconfirm
          class="ml-5"
          confirm-button-text='确定'
          cancel-button-text='我再想想'
          icon="el-icon-info"
          icon-color="red"
          title="您确定批量删除这些数据吗？"
          @confirm="delBatch"
      >
        <template v-slot:reference>
          <el-button type="danger">批量删除 <i class="el-icon-remove-outline"></i></el-button>
        </template>
      </el-popconfirm>
    </div>

    <!-- 上传文件 -->
    <div style="margin: 10px 0">
      <input type="file" @change="handleFileUpload" />
      <el-button style="margin-left: 5px" type="primary" @click="submitFile"><i class="el-icon-upload"></i> 上传文件</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="编号" width="180"></el-table-column>
      <el-table-column prop="name" label="文件名" width="180"></el-table-column>
      <el-table-column prop="url" label="链接"></el-table-column>
      <el-table-column prop="createtime" label="创建时间"></el-table-column>
      <el-table-column prop="updatetime" label="更新时间"></el-table-column>
      <el-table-column label="文件" width="250">
        <template v-slot="scope">
          <el-button type="primary" @click="downloadFile(scope.row.name)">下载</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template v-slot="scope">
          <el-button type="primary" @click="handEdit(scope.row)">编辑</el-button>
          <el-popconfirm
              style="margin-left: 5px"
              title="您确定删除这行数据吗？"
              @confirm="del(scope.row.id)"
          >
            <template v-slot:reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="信息" v-model="dialogVisible" width="40%" :before-close="handleClose">
      <el-form label-width="120px" style="width: 80%; margin: 0 auto">
        <el-form-item prop="name" label="文件名">
          <el-input v-model:modelValue="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="url" label="链接">
          <el-input v-model:modelValue="form.url" autocomplete="off"></el-input>
        </el-form-item>
    
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-pagination
        style="justify-content: center;margin-top: 20px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    ></el-pagination>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import request from "@/utils/request";
import {ElMessage} from "element-plus";
import axios from 'axios';
import { useRouter } from "vue-router";
const router=useRouter()
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(5);
const dialogVisible = ref(false);
const tableData = ref([]);
const multipleSelection = ref([]);
const username = ref('');
const form = ref({
  name: '',
  content: '',
  userId: '',
  fileName: ''
});

const selectedFile = ref(null);

onMounted(() => {
  loadAdminPage();
});


const save = async () => {
  const res = await request.post("/document/save", form.value);
  if (res.data.code === '200') {
    ElMessage.success("修改成功");
    dialogVisible.value = false;
    loadAdminPage();
  } else {
    ElMessage.error("修改失败");
  }
};
const del = async (id) => {
  const res = await request.delete(`/document/${id}`);
  if (res.data.code === '200') {
    ElMessage.success('删除成功');
    loadAdminPage();
  } else {
    ElMessage.error("删除失败");
  }
};

const reset = () => {
  username.value = '';
  loadAdminPage();
};

const loadAdminPage = async () => {
  try {
    const res = await request.get('/document/page', {params: {pageNum: pageNum.value, pageSize: pageSize.value, username: username.value}});
    tableData.value = res.data.data.records;
    total.value = res.data.data.total;
    console.log("----", res.data.data);
    console.log("----", total.value);
  } catch (error) {
    if (error.response) {
    // 请求已发出，但服务器响应了状态码不在2xx范围内的内容
    console.error('服务器响应错误:', error.response.status, error.response.data);
    // 你可以根据状态码做不同的处理
    if (error.response.status === 402 || error.response.status === 405) {
      // 处理405错误
    localStorage.removeItem('token')
    localStorage.removeItem('userName')
    localStorage.removeItem('menus')
    localStorage.removeItem('userType')
    // 重定向到登录页面
    router.push('/login')
    }
  } else if (error.request) {
    // 请求已发出，但没有收到响应
    console.error('请求已发送，但未收到响应:', error.request);
  } else {
    // 其他错误（如配置错误导致请求未发送）
    console.error('错误:', error.message);
  }
  }
};

const handEdit = (row) => {
  form.value = JSON.parse(JSON.stringify(row));
  dialogVisible.value = true;
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  loadAdminPage();
};

const handleCurrentChange = (val) => {
  pageNum.value = val;
  loadAdminPage();
};

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const delBatch = async () => {
  if (!multipleSelection.value.length) {
    ElMessage.error("请选择需要删除的数据");
    return;
  }

  const ids = multipleSelection.value.map(v => v.id);
  console.log("++++", ids);
  try {
    const res = await request.post("/document/del/batch", ids);
    if (res.data.code === '200') {
      ElMessage.success('批量删除成功');
      loadAdminPage();
    } else {
      ElMessage.error("批量删除失败");
    }
  } catch (error) {
    console.error('批量删除错误:', error);
    ElMessage.error("批量删除失败，请重试");
  }
};

const handleFileUpload = (event) => {
  selectedFile.value = event.target.files[0];
};

const submitFile = async () => {
  if (!selectedFile.value) {
    ElMessage.error("请选择文件");
    return;
  }

  const formData = new FormData();
  formData.append("file", selectedFile.value);

  try {
    const res = await axios.post("http://localhost:9090/apiOne/document/upload", formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    console.log('-------',res);
    if (res.data === "文件上传成功") {
      ElMessage.success("文件上传成功");
      loadAdminPage();
    } else {
      ElMessage.error("文件上传失败");
    }
  } catch (error) {
    console.error("文件上传错误:", error);
    ElMessage.error("文件上传失败，请重试");
  }
};

const downloadFile = (name) => {
  // window.open(url)
  window.open(`http://localhost:9090/apiOne/document/export?name=${name}`)
};

</script>

<style scoped>
.container { }
</style>

  